package org.jeecg.modules.tankerRegistration.util;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.nlp.v2.NlpClient;
import com.huaweicloud.sdk.nlp.v2.model.*;
import com.huaweicloud.sdk.nlp.v2.region.NlpRegion;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.*;
import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HuaweiCloudUtil {

    private static final String ak = "OCQBKUTBWRIHW4O6YFX1";
    private static final String sk = "CKcFXmgrYETxxMoUw3UPJfI9igbTttO2xYqcmrNK";
    private static final ICredential auth = new BasicCredentials()
            .withAk(ak)
            .withSk(sk);
    private static final OcrClient ocrClient = OcrClient.newBuilder()
            .withCredential(auth)
            .withRegion(OcrRegion.valueOf("cn-north-4"))
            .build();

    private static final NlpClient nlpClient = NlpClient.newBuilder().withCredential(auth)
            .withRegion(NlpRegion.valueOf("cn-north-4"))  //配置region信息，目前只支持北京四 cn-north-4
            .build();

    /**
     * 通用识别表格
     *
     * @param url 图片路径
     * @return
     */
    public static RecognizeGeneralTableResponse recognizeGeneralTable(String url) {
        RecognizeGeneralTableRequest request = new RecognizeGeneralTableRequest();
        GeneralTableRequestBody body = new GeneralTableRequestBody();
        body.withUrl(url); // 使用传入的URL参数
        request.withBody(body);
        try {
            return ocrClient.recognizeGeneralTable(request);
        } catch (Exception e) {
            log.error("OCR请求异常", e);
        }
        return null;
    }

    /**
     * 身份证识别
     *
     * @param url 图片路径
     * @return
     */
    public static RecognizeIdCardResponse recognizeIdCard(String url) {
        RecognizeIdCardRequest request = new RecognizeIdCardRequest();
        IdCardRequestBody body = new IdCardRequestBody();
        body.withDetectCopy(true);
        body.withDetectReproduce(true);
        body.withReturnTextLocation(true);
        body.withReturnVerification(true);
        body.withSide("front");
        body.withUrl(url);
        request.withBody(body);
        try {
            return ocrClient.recognizeIdCard(request);
        } catch (Exception e) {
            log.error("OCR请求异常", e);
        }
        return null;
    }

    /**
     * 行驶证识别
     *
     * @param url 图片路径
     * @return
     */
    public static RecognizeVehicleLicenseResponse recognizeVehicleLicense(String url) {
        RecognizeVehicleLicenseRequest request = new RecognizeVehicleLicenseRequest();
        VehicleLicenseRequestBody body = new VehicleLicenseRequestBody();
        body.withReturnIssuingAuthority(true);
        body.withSide("front");
        body.withUrl(url);
        request.withBody(body);
        try {
            return ocrClient.recognizeVehicleLicense(request);
        } catch (Exception e) {
            log.error("OCR请求异常", e);
        }
        return null;
    }

    /**
     * 智能文档解析
     *
     * @param url 图片路径
     * @return
     */
    public static RecognizeSmartDocumentRecognizerResponse recognizeSmartDocumentRecognizer(String url) {
        Map<String, String> map = new HashMap<>();
        RecognizeSmartDocumentRecognizerRequest request = new RecognizeSmartDocumentRecognizerRequest();
        SmartDocumentRecognizerRequestBody body = new SmartDocumentRecognizerRequestBody();
        body.withUrl(url);
        request.withBody(body);
        try {
            RecognizeSmartDocumentRecognizerResponse response = ocrClient.recognizeSmartDocumentRecognizer(request);
            return response;
        } catch (Exception e) {
            log.error("OCR处理异常", e);
        }
        return null;
    }

    /**
     * 通用文字识别
     *
     * @param url 图片路径
     * @return
     */
    public static RecognizeGeneralTextResponse recognizeGeneralText(String url) {
        RecognizeGeneralTextRequest request = new RecognizeGeneralTextRequest();
        GeneralTextRequestBody body = new GeneralTextRequestBody();
        body.withUrl(url);
        request.withBody(body);
        try {
            RecognizeGeneralTextResponse response = ocrClient.recognizeGeneralText(request);
            return response;
        } catch (Exception e) {
            log.error("OCR处理异常", e);
        }
        return null;
    }

    public static String handleGeneralTableDataOfOcr(RecognizeGeneralTableResponse response) {
        if (response == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        GeneralTableResult result = response.getResult();
        List<WordsRegionList> wordsRegionList = result.getWordsRegionList();
        for (WordsRegionList wordsRegion : wordsRegionList) {
            List<GeneralTableWordsBlockList> wordsBlockList = wordsRegion.getWordsBlockList();
            for (GeneralTableWordsBlockList wordsBlock : wordsBlockList) {
                String s = wordsBlock.getWords().replaceAll("\n", "").trim();
                stringBuilder.append(s);
            }
        }
        return stringBuilder.toString();
    }

    public static void handleGeneralTextDataOfOcr(RecognizeGeneralTextResponse response) {
        StringBuilder stringBuilder = new StringBuilder();
        GeneralTextResult result = response.getResult();
        List<GeneralTextWordsBlockList> wordsBlockList = result.getWordsBlockList();
        for (GeneralTextWordsBlockList wordsBlock : wordsBlockList) {
            String s = wordsBlock.getWords().replaceAll("\n", "").trim();
            stringBuilder.append(s);
        }
        System.out.println(stringBuilder);
    }

    //文本相似度(基础版)
    public static RunTextSimilarityResponse runTextSimilarity(String text1, String text2) {
        TextSimilarityRequest req1 = new TextSimilarityRequest();
        req1.setText1(text1);
        req1.setText2(text2);
        req1.setLang(TextSimilarityRequest.LangEnum.fromValue("zh"));
        RunTextSimilarityRequest req2 = new RunTextSimilarityRequest();
        req2.setBody(req1);

        try {
            return nlpClient.runTextSimilarity(req2);
        } catch (Exception e) {
            log.error("文本相似度处理异常", e);
        }
        return null;
    }

    //文本相似度(高级版)
    public static RunTextSimilarityAdvanceResponse runTextSimilarityAdvance(String text1, String text2) {
        TextSimilarityAdvanceRequest req1 = new TextSimilarityAdvanceRequest();
        req1.setText1(text1);
        req1.setText2(text2);
        req1.setLang(TextSimilarityAdvanceRequest.LangEnum.fromValue("zh"));
        RunTextSimilarityAdvanceRequest req2 = new RunTextSimilarityAdvanceRequest();
        req2.setBody(req1);
        try {
            return nlpClient.runTextSimilarityAdvance(req2);
        } catch (Exception e) {
            log.error("文本相似度处理异常", e);
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("plateNo", "冀B9857M");
        params.put("begintime", "2025-03-24 00:00:00");
        params.put("endtime", "2025-03-25 00:00:00");
        params.put("plateColor", "2");
        try {
            // 使用 OkHttp
            String response = sendPost("https://enviroment.tw-tj.com:2443/NewElefence/GetRoutePath", params);
            System.out.println("Response: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final MediaType FORM_URLENCODED = MediaType.get("application/x-www-form-urlencoded");

    public static String sendPost(String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // 构建请求体
        FormBody.Builder formBuilder = new FormBody.Builder();
        params.forEach(formBuilder::add);
        RequestBody body = formBuilder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code: " + response);
            }
            return response.body().string();
        }
    }

}
